import os
import sys

pwd = os.getcwd()

print(pwd)
try:
    data = open('sketch.txt')
    # print(data.readline(), end='')
    # print(data.readline(), end='')
    #
    # data.seek(0)  # 返回文件起始位置。

    man = []  # 空列表
    other = []  # 空列表

    for line in data:
        # if line.find(':') is not -1:
        try:
            (role, line_spoken) = line.split(':', 1)
            # 除去空白符后的字符串，再赋回到自身
            line_spoken = line_spoken.strip()
            # 根据某人讲话，更新列表
            if role == 'Man':
                man.append(line_spoken)
            # elif表示else if
            elif role == 'Other Man':
                other.append(line_spoken)
        except ValueError:
            pass
    data.close()
except IOError:
    print('The data is missing')


print(man)
print(other)


def print_lol(the_list, indent=False, level=0, fh=sys.stdout):
    for e in the_list:
        if isinstance(e, list):
            print_lol(e, indent, level + 1, fh)
        else:
            if indent:
                for tab_stop in range(level):
                    print("\t", end='', file=fh)
            print(e, file=fh)


# try:
#     man_file = open('man.txt', 'w')
#     other_file= open('other.txt', 'w')
#     print(man, file=man_file)
#     print(other, file=other_file)
#
# except IOError:  # IO异常
#     print('file error')
# finally:  #  保证文件关闭
#     man_file.close()
#     other_file.close()

try:
    with open('man.txt', 'w') as man_file:
        print(man, file=man_file)
    with open('other.txt', 'w') as other_file:
        print(other, file=other_file)
    with open('man_1.txt', 'w') as man_file1, open('other_1.txt', 'w') as other_file2:
        print_lol(man, fh=man_file1)
        print_lol(other, fh=other_file2)
except IOError as err:
    print('File Error ' + str(err))

try:
    data_miss = open('missing.txt')
    print(data_miss.readline(), end='')
except IOError as err:
    print('File Error' + str(err))
finally:
    if 'data_miss' in locals():  # 返回当前作用域中定义的所有名的一个集合
        data_miss.close()
